package com.xhy.documents_collection.controller;

import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.entity.PO.task.DownloadRecord;
import com.xhy.documents_collection.exception.BaseException;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.service.task.DownloadRecordService;
import com.xhy.documents_collection.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: Xhy
 * CreateTime: 2022-11-16 14:23
 */
@Controller
public class IndexController {



    public static String url;

    @Resource
    DownloadRecordService downloadRecordService;

    @Value("${url}")
    public void setUrl(String url) {
        this.url = url+":";
    }

    @RequestMapping("/")
    public void loginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(url+request.getServerPort()+"/page/login.html");
    }

    // 根据邮箱中的url进行下载
    @GetMapping("/download/{id}")
    @ResponseBody
    public String getUrlBySTS(@PathVariable String id) throws Exception {

        DownloadRecord downloadRecord = downloadRecordService.getById(id);
        String filePath = downloadRecord.getFilePath();
        Integer downloadSize = downloadRecord.getDownloadSize();
        if (ObjectUtils.isEmpty(filePath) || ObjectUtils.isEmpty(downloadSize)){
            throw new Exception("不合法");
        }
        if (downloadSize == 0){
            throw new BaseException(500,"下载次数达到限制,如还要下载,联系:<your info>");
        }

        downloadRecord.setDownloadSize(downloadSize-1);
        downloadRecordService.updateById(downloadRecord);
        return "<h2>正在下载...进度:<span id=\"jindu\"></span></h2>" +
                "<script>" +
                "var xhr = new XMLHttpRequest();\n" +
                "\n" +
                "// 设置要请求的URL和请求类型\n" +
                "xhr.open(\"GET\", \""+OSSUtil.getUrlBySTS(filePath)+"\", true);\n" +
                "\n" +
                "// 将referrer添加到请求头中\n" + // TODO 设置防盗链 可选
                "xhr.setRequestHeader(\"Referer\", \"<your referer>\");\n" +
                "xhr.setRequestHeader(\"Access-Control-Allow-Origin\", \"*\");\n" +
                "xhr.responseType=\"blob\";\n"+
                "xhr.onload = function() {\n" +
                "  if (xhr.status === 200) {\n" +
                "    // 获取响应文档\n" +
                "    var blob = xhr.response;\n" +
                "\n" +
                "    // 创建一个FileReader对象\n" +
                "    var reader = new FileReader();\n" +
                "\n" +
                "    // 注册事件处理程序，在读取完成时保存文件\n" +
                "    reader.onloadend = function() {\n" +
                "      // 获取文件名\n" +
                "      var filename = \""+downloadRecord.getFileName()+"\";\n" +
                "\n" +
                "      // 创建一个<a>元素，并设置download属性\n" +
                "      var a = document.createElement(\"a\");\n" +
                "      a.download = filename;\n" +
                "\n" +
                "      // 将Blob数据转换为URL，并设置href属性\n" +
                "      a.href = URL.createObjectURL(blob);\n" +
                "\n" +
                "      // 模拟点击<a>元素来下载文件\n" +
                "      a.click();\n" +
                "    };\n" +
                "\n" +
                "    // 读取Blob数据\n" +
                "    reader.readAsDataURL(blob);\n" +
                "  }\n" +
                "};" +
                "// 发送请求\n" +
                "var percentComplete=0;" +
                "xhr.addEventListener(\"progress\", function(event) {\n" +
                "  if (event.lengthComputable) {\n" +
                "     percentComplete= (event.loaded / event.total) * 100;\n" +
                "    // 更新进度条或百分比\n" +
                "    console.log(percentComplete);\n" +
                "document.getElementById(\"jindu\").innerHTML=percentComplete+\"%\""+
                "  }\n" +
                "});"+
                "xhr.send();" +
                "</script>";
    }

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/temp")
    public R userTemp(){
        Map<String, String> map = new HashMap<>();
        map.put("email","123@qq.com");
        map.put("userName","张三");
        map.put("studentNumber","123456");
        return R.ok().data("data",map);
    }

    @ResponseBody
    @PostMapping("/user/update")
    public R updateUser(@RequestBody User user,HttpServletRequest request){

        user.setId(Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request)));
        return userService.updateUser(user);
    }

    @GetMapping("/user/get")
    @ResponseBody
    public R getUser(HttpServletRequest request){
        String uId = JwtUtils.getMemberIdByJwtToken(request);
        return R.ok().data("data",userService.getById(uId));
    }

    @PostMapping("/parseTemp")
    @ResponseBody
    public R parseTemp(String template,HttpServletRequest request){

        if (!Template.verify(template)){
            return R.error().message("模板不合规");
        }
        String uId = JwtUtils.getMemberIdByJwtToken(request);
        if (ObjectUtils.isEmpty(uId)){
            return R.error().message("请登录以后再访问");
        }
        User user = userService.getById(uId);
        String parseTemp = null;
        try {
            parseTemp = Template.parseTemp(template, user);
        } catch (Exception e) {
            return R.error().message("没有这样的字段");
        }
        return R.ok().message(parseTemp);
    }



}
